import sys
import os
from http import HTTPStatus

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, ".."))
sys.path.append(os.path.join(thisDir, "..", "..", "common"))
sys.path.append(os.path.join(thisDir, "..", "..", "ui", "pu"))

import PUConst
import EJOConst
from SessionManager import SessionManager
from EJOHandlerBase import EJOHandlerBase

import logging
logger = logging.getLogger(__name__)

class EJOPage(EJOHandlerBase):
    def _doValidate(self):
        pageId = self._getParamValue("id")
        session = self._getParamValue("session")
        return True if pageId == EJOConst.PageLogin else SessionManager().IsValidSession(session)

    def _doHandle(self):
        logger.debug(f"Handled by: {__name__}")

        pageId = self._getParamValue("id")
        try:
            pageId = int(pageId)
        except Exception as e:
            return True, HTTPStatus.BAD_REQUEST, f"Exception on page id: {pageId}"

        client = self._getParamValue("client")
        session = self._getParamValue("session")
        if not self.__isValidPageId(pageId):
            return True, HTTPStatus.BAD_REQUEST, f"Invalid page id: {pageId}"
        if not self.__isValidClent(client):
            return True, HTTPStatus.BAD_REQUEST, f"Invalid client: {client}"
        return self.__generateLoginPage(client) if pageId == EJOConst.PageLogin else self.__generatePage(client, pageId, session)

    def __isValidPageId(self, pageId):
        return pageId in EJOConst.PageIds

    def __isValidClent(self, client):
        return client == EJOConst.ClientHtml

    def __generateLoginPage(self, client):
        pu = SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_UI)
        page = pu.Generate(client, PUConst.UiBody, uidMain = "uidLogin")
        if page is not None:
            return True, HTTPStatus.OK, page
        return True, HTTPStatus.INTERNAL_SERVER_ERROR, "Create login page fail"

    def __generatePage(self, client, pageId, session):
        pu = SessionManager().GetProperty(EJOConst.SESSION_PROPERTY_UI)
        page = pu.Generate(client, PUConst.UiBody, uidMain = "uidPages", uidPage = EJOConst.PageIds[pageId])
        if page:
            return True, HTTPStatus.OK, page
        return True, HTTPStatus.INTERNAL_SERVER_ERROR, f"Create page fail: {pageId}"
